# coding: utf-8
import re
import os

class DelphiParser(object):

    def file_extensions(self):
        return ['pas',]

    def get_name(self, name):
        return '.'.join(os.path.basename(name).split('.')[:-1]).lower()

    def parse(self, content):
        """Deve retornar as dependências no formato de um dicionário::
        {
          'interface': ['sysutils', 'venda.desconto', 'venda.totais',],
          'implementation': ['venda.item', 'venda.controlador', 'typinfo',],
        }

        Retorna o uses de uma unit delphi separando interface de implementation.

        >>> source = '''
        ... unit a;
        ... interface
        ... uses
        ...   classes, sysutils;
        ... implementation
        ... uses
        ...   venda.vendavel,
        ...   TypInfo;
        ... procedure SomeProcedure;
        ... begin
        ... //Some code
        ... end;
        ... end.'''
        >>> p = DelphiParser()
        >>> p.parse(source)
        {'interface': ['classes', 'sysutils'], 'implementation': ['venda.vendavel', 'typinfo']}
        """
        result = {}
        m = re.findall(r'uses([\w\s,\.\n]+);', content, re.MULTILINE)

        f = lambda x: [u.lower() for u in re.findall(r'([\w.]+)', x)]
        if m:
            result['interface'] = f(m[0])
            if len(m) == 2:
                result['implementation'] = f(m[1])

        return result


if __name__ == "__main__":
    import doctest
    doctest.testmod()